package com.gd.demo.cloud.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 自定义一个全局过滤器
 * 实现 globalfilter , ordered接口
 *
 * @author ligoudan
 */
//@Component
//@Order(-1)
//public class DemoFilter implements GlobalFilter {
//
//    private static final Log log = LogFactory.getLog(DemoFilter.class);
//
//    /**
//     * 执行过滤器中的业务逻辑
//     * 对请求参数中的access-token进行判断
//     * 如果存在此参数:代表已经认证成功
//     * 如果不存在此参数 : 认证失败.
//     * ServerWebExchange : 相当于请求和响应的上下文(zuul中的RequestContext)
//     */
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        log.info("全局过滤器----请求地址:" + exchange.getRequest().getURI());
//        ServerHttpRequest req = exchange.getRequest();
//        //获取域名后的path
//        String rawPath = req.getURI().getRawPath();
//        URI uri = UriComponentsBuilder.fromHttpUrl("http://news.baidu.com" + rawPath).build().toUri();
//
//        //重新封装request对象
//        ServerHttpRequest request = req.mutate().uri(uri).build();
////        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
//        boolean encoded = ServerWebExchangeUtils.containsEncodedParts(uri);
////        URI routeUri = route.getUri();
////        URI mergedUrl = UriComponentsBuilder.fromUri(uri)
////                .scheme(routeUri.getScheme())
////                .host(routeUri.getHost())
////                .port("80")
////                .build(encoded)
////                .toUri();
//
//
//        URI mergedUrl = UriComponentsBuilder.fromUri(uri)
//                .scheme(uri.getScheme())
//                .host(uri.getHost())
//                .port("80")
//                .build(encoded)
//                .toUri();
//        //NettyRoutingFilter 最终会从GATEWAY_REQUEST_URL_ATTR 取出uri对象进行http请求，所以这里需要将新的对象覆盖进去
//        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, mergedUrl);
//        return chain.filter(exchange.mutate().request(request).build()).then(Mono.fromRunnable(() -> {
//            //请求完成回调方法 可以再此完成计算请求耗时等操作
//        }));
//    }
//}
